<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="webpack,hmr,教程,热拔插," />





  <link rel="alternate" href="/atom.xml" title="Da'sBlog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="http://andrewhfarmer.com/webpack-hmr-tutorial/Struggling to set up HMR with Webpack? Are you finding the Webpack documentation to be lacking - particularly in the HMR section? Does it seem like they’v">
<meta name="keywords" content="webpack,hmr,教程,热拔插">
<meta property="og:type" content="article">
<meta property="og:title" content="webpack热拔插教程hmr">
<meta property="og:url" content="http://sunhao.win/articles/webpack-hmr-tutorial.html">
<meta property="og:site_name" content="Da&#39;sBlog">
<meta property="og:description" content="http://andrewhfarmer.com/webpack-hmr-tutorial/Struggling to set up HMR with Webpack? Are you finding the Webpack documentation to be lacking - particularly in the HMR section? Does it seem like they’v">
<meta property="og:updated_time" content="2017-03-07T06:17:26.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="webpack热拔插教程hmr">
<meta name="twitter:description" content="http://andrewhfarmer.com/webpack-hmr-tutorial/Struggling to set up HMR with Webpack? Are you finding the Webpack documentation to be lacking - particularly in the HMR section? Does it seem like they’v">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://sunhao.win/articles/webpack-hmr-tutorial.html"/>





  <title> webpack热拔插教程hmr | Da'sBlog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8432f1a5c5c27d6783c25569df4b270";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Da'sBlog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <h1 class="site-subtitle" itemprop="description"></h1>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>
<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">


        
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
        


      
        
        <li class="menu-item menu-item-categories">


        
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
        


      
        
        <li class="menu-item menu-item-archives">


        
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
        


      
        
        <li class="menu-item menu-item-compass">


        
          <a href="/2017/01/11/compass" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th-list"></i> <br />
            
            compass中文手册
          </a>
        </li>
        


      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://sunhao.win/articles/webpack-hmr-tutorial.html">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Sun Hao">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Da'sBlog">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="Da'sBlog" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">
            
            
              
                webpack热拔插教程hmr
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-03-07T08:50:58+08:00">
                2017-03-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index">
                    <span itemprop="name">webpack</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/articles/webpack-hmr-tutorial.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><a href="http://andrewhfarmer.com/webpack-hmr-tutorial/" target="_blank" rel="external">http://andrewhfarmer.com/webpack-hmr-tutorial/</a><br>Struggling to set up HMR with Webpack?</p>
<p>Are you finding the Webpack documentation to be lacking - particularly in the HMR section? Does it seem like they’ve left out some important parts?</p>
<p>If so, read on! We’ll fill in the gaps together.</p>
<p>By the way, HMR stands for ‘Hot Module Replacement’, sometimes called ‘hot module swapping’. It’s a Webpack feature that updates your JavaScript in-place without a browser refresh - whenever you make code changes. I love it because it enables a very fast developer workflow.<br>HMR Myths<br>First let’s get a couple myths about HMR out of the way.<br><a id="more"></a><br>Myth: HMR is only for React<br>Not true - it usually just takes 3 lines of code to enable HMR in arbitrary JavaScript. This Tutorial doesn’t even mention React - I’ll cover HMR in React in a subsequent post.</p>
<p>Myth: HMR is only for ‘advanced’ users<br>Not true. Without good documentation, HMR is difficult for beginners and advanced users alike. With the right information (this article), HMR can be enabled with very minor changes to config/code.</p>
<p>Myth: HMR is the same as ‘live reload’<br>Not true. Live reload is when the browser automatically refreshes the page whenever you make a code change. HMR is faster because it updates code in-place without refreshing.</p>
<p>2 Steps to HMR Success<br>There are 2 steps to enabling HMR: config changes and code changes.</p>
<ol>
<li><p>Config / Project Setup<br>There are 3 ways to configure your project for HMR. I go into each way in detail in Part 1. Pick the way that’s right for you and either use the provided github repository, or follow the directions to adapt your existing code base.</p>
</li>
<li><p>JavaScript / HMR API<br>To get HMR to work you have to add a little bit of extra code to your JavaScript. In the simplest case this is just 3 lines of code. I’ll show you everything you need to add for your use-case in Part 2.</p>
</li>
</ol>
<p>Part 1: Configuring Your Project<br>There are exactly 3 ways that you can configure your HMR project. Let’s go through each one. I’ll help you pick which one to use in the next section.</p>
<ol>
<li><p>webpack-dev-server CLI<br>Run the webpack-dev-server on the command-line. With this approach you don’t need to change your webpack.config.js file, so it’s the simplest.</p>
</li>
<li><p>webpack-dev-server API<br>Run WebpackDevServer from a node.js script. Requires some additions to your webpack.config.js.</p>
</li>
<li><p>webpack-hot-middleware w/ express<br>webpack-hot-middleware is used for running a webpack dev server with HMR inside an express server.</p>
</li>
</ol>
<p>The Non-Way<br>If you are used to running the webpack CLI or the Webpack API (without express or webpack-dev-server), then you’ll have to change how you do things a little bit. HMR requires a server to work. To find out why, read my understanding HMR post.</p>
<p>But how do I choose?<br>Follow this simple guide to pick one of the 3 ways above.</p>
<p>If you are using a task runner like grunt or gulp you’ll want to use the webpack-dev-server API. You can run the server from one of your gulp/grunt tasks.</p>
<p>If you use your own node scripts to run webpack, you’ll also want to use the webpack-dev-server API.</p>
<p>If you use express to host your site: use webpack-hot-middleware. It will be integrated with your express server, so you won’t have to run another server for your bundled JS.</p>
<p>If none of the above apply to you or you just want the simplest possible setup: use the webpack-dev-server CLI. It requires no configuration.</p>
<p>Okay, I picked one, but how do I start?<br>Glad you asked! Below is a separate ‘Configuring X’ section for each of the 3 approaches.</p>
<p>Scroll forward to the approach you decided to use, follow the directions, and then scroll down to Part 2.</p>
<ol>
<li>Configuring webpack-dev-server CLI<br>Read this section if you’ve decided to use the webpack-dev-server CLI. Otherwise, scroll to the next section.</li>
</ol>
<p>If you are starting a new project, use my webpack HMR with webpack-dev-server CLI starter project (wow that’s a mouthful). It has a README and lots of comments to explain what’s going on.</p>
<p>If you are working with an existing project: just make sure you have a valid webpack.config.js and run webpack-dev-server.</p>
<p>Here’s an example command:</p>
<p>webpack-dev-server –content-base=www –inline –watch –hot<br>You may want to modify the above command for your use-case based on the CLI Docs.</p>
<p>That’s it! When you use the webpack-dev-server CLI it does all the configuration for you.</p>
<p>Gotcha: When using this approach, make sure your webpack.config.js does NOT contain any references to webpack-dev-server or HotModuleReplacementPlugin. You’ll get errors if you do.</p>
<ol>
<li>Configuring WebpackDevServer API<br>Read this section if you’ve decided to use the WebpackDevServer API. Otherwise, scroll to the next section.</li>
</ol>
<p>If you are starting a new project, use my webpack HMR with WebpackDevServer API starter project. It has a README and lots of comments to explain what’s going on.</p>
<p>If you are working with an existing project, you’ll have to make 3 changes:</p>
<p>Change #1: Add entry points to your webpack.config.js. Here’s an example. You need webpack/hot/dev-server and webpack-dev-server/client as shown, but index.js should be the name of your usual entry point.</p>
<p>entry: [<br>  ‘./index.js’,<br>  ‘webpack/hot/dev-server’,<br>  ‘webpack-dev-server/client?<a href="http://localhost:8080/" target="_blank" rel="external">http://localhost:8080/</a>‘,<br>],<br>Change #2: Add the HotModuleReplacementPlugin to your your webpack.config.js, like this:</p>
<p>plugins: [<br>  new webpack.HotModuleReplacementPlugin(),<br>]<br>For a complete example, see the starter project webpack.config.js.</p>
<p>Change #3: Run WebpackDevServer with the hot: true option. For an example, see the starter project server.js.</p>
<ol>
<li>Configuring webpack-hot-middleware &amp; express<br>Read this section if you’ve decided to use express and webpack-hot-middleware. Otherwise, scroll on to Part 2.</li>
</ol>
<p>If you are starting a new project, use my webpack HMR with webpack-hot-middleware &amp; express starter project. It has a README and lots of comments to explain what’s going on.</p>
<p>If you are working with an existing express project, you’ll need to do 3 things:</p>
<p>Change #1: Install webpack-hot-middleware and webpack-dev-middleware. I’m assuming you already have webpack and express.</p>
<p>npm install –save-dev webpack-hot-middleware webpack-dev-middleware<br>Change #2: Adjust your webpack.config.js to look similar to this. The important bits are the entry and plugins section. You’ll want all the plugins I have listed:</p>
<p>var path = require(‘path’);<br>var webpack = require(‘webpack’);</p>
<p>var config = {<br>  context: path.join(<strong>dirname, ‘js’),<br>  entry: [<br>    ‘webpack-hot-middleware/client?path=/</strong>webpack_hmr&amp;timeout=20000’,<br>    ‘./index.js’,<br>  ],<br>  output: {<br>    path: path.join(__dirname, ‘www’),<br>    filename: ‘bundle.js’,<br>    publicPath: ‘/assets/‘,<br>  },<br>  plugins: [<br>    new webpack.optimize.OccurenceOrderPlugin(),<br>    new webpack.HotModuleReplacementPlugin(),<br>    new webpack.NoErrorsPlugin()<br>  ]<br>};<br>module.exports = config;<br>Change #3: Add the middleware to your express server.</p>
<p>Add these requires:</p>
<p>var webpackDevMiddleware = require(“webpack-dev-middleware”);<br>var webpackHotMiddleware = require(“webpack-hot-middleware”);<br>And these middleware .use statements:</p>
<p>app.use(webpackDevMiddleware(compiler, {<br>  hot: true,<br>  filename: ‘bundle.js’,<br>  publicPath: ‘/assets/‘,<br>  stats: {<br>    colors: true,<br>  },<br>  historyApiFallback: true,<br>}));</p>
<p>app.use(webpackHotMiddleware(compiler, {<br>  log: console.log,<br>  path: ‘/__webpack_hmr’,<br>  heartbeat: 10 * 1000,<br>}));<br>Part 2: Code Changes<br>Your Webpack project should now be configured for HMR. But if you fire up a browser at this point and make a code change, it won’t work. Either you won’t see the update, or you’ll get a full browser refresh.</p>
<p>Why isn’t it working yet? Webpack doesn’t know when it is acceptable to reload a particular JS file.</p>
<p>To let Webpack know which files can be updated, we’ll use the HMR JavaScript API a.k.a. the module.hot API.</p>
<p>If you used any of my github starter projects, they are already using the module.hot API and you will see changes reflected immediately.<br>The Simple Way<br>To start, find your entry point (often called index.js or main.js) and add the following to the end:</p>
<p>if (module.hot) {<br>  module.hot.accept();<br>}<br>This tells Webpack that this file and all of its dependencies can be replaced.</p>
<p>Now make a code change that you could see the effect of onscreen. You SHOULD have seen an update!</p>
<p>For many projects, that’s all there is to it.</p>
<p>The Catch: Side Effects<br>If any of your files produce side effects when they run, for instance if they add elements to the DOM, then you’ll need to use module.hot.dispose to dispose of those side effects.</p>
<p>Why? If you don’t, when Webpack reloads the module, all the side effects will be repeated.</p>
<p>Here’s an example, box-creator.js:</p>
<p>var sideEffectNode = document.createElement(‘div’);<br>sideEffectNode.textContent = ‘Side Effect’;<br>document.body.appendChild(sideEffectNode);</p>
<p>// Remove the most recently-added <div> so that when the code runs again and<br>// adds a new <div>, we don’t end up with duplicate divs.<br>if (module.hot) {<br>  module.hot.dispose(function() {<br>    sideEffectNode.parentNode.removeChild(sideEffectNode);<br>  });<br>}<br>This is a file that simply adds a <div> to the DOM whenever it is loaded. It uses module.hot.dispose to remove the <div> when it is unloaded by the Webpack HMR Runtime.</div></div></div></div></p>
<p>Conclusion<br>That’s all you need to know to get HMR working. If you want to dig deeper to solidify your understanding, read my article on understanding HMR.</p>
<p>Coming soon: next I’ll post about how to apply HMR to your React project. Sign up for my list to be notified when that comes out!</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/webpack/" rel="tag"># webpack</a>
          
            <a href="/tags/hmr/" rel="tag"># hmr</a>
          
            <a href="/tags/教程/" rel="tag"># 教程</a>
          
            <a href="/tags/热拔插/" rel="tag"># 热拔插</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/articles/laravel-study.html" rel="next" title="laravel学习零散知识点">
                <i class="fa fa-chevron-left"></i> laravel学习零散知识点
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/articles/php-class-type-declaration.html" rel="prev" title="php函数参数类和接口">
                php函数参数类和接口 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Sun Hao" />
          <p class="site-author-name" itemprop="name">Sun Hao</p>
          <p class="site-description motion-element" itemprop="description">Whoever wants to be first must be slave of all.</p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">40</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">69</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sun Hao</span>
</div>


<div class="powered-by">
  Erstellt mit  <a class="theme-link" href="https://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user">本站访客数</i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人次</span>
  

  
    <span class="site-pv"><i class="fa fa-eye">本站总访问量</i><span class="busuanzi-value" id="busuanzi_value_site_pv"></span>次</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "68d47669d3794a958fbaaee9328b90f3",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  







  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  


</body>
</html>
